<?php
/**
 * vim: et ts=4 sts=4 sw=4 fdm=marker
 *
 * 事件触发器 -- 支持命令行运行	 
 *
 * @author	wang Penghai <china_php@hotmail.com>
 * @copyright 2008 5e6d Corporation.
 * @version   $Id: config.php 29 2009-03-10 14:30:18Z wph $
 */

class pf_action {

	/**
	 * 类成员变量
	 */
	//controller 路径--相对APP_PATH
	protected $_controller_path = '';
	//controller 扩展名
	protected $_controller_ext = '_action';
	//是否是命令行执行
	protected $_is_shell = false;
	/**
	 * 参数设置 --  不作过滤
	 * 
	 * @param array $params 参数数组
	 */
	public function param_set($params)
	{
		//$params = array_map(, $params);//只要英文
		//controller 扩展
		if (isset($params['c_ext']))
		{
			$this->_controller_ext = $params['c_ext'];
		}
		//controller 路径
		if (isset($params['c_path']))
		{
			$this->_controller_path = '/' . $params['c_path'] . '/';
		}
		//是否是命令行执行
		if (isset($params['is_shell']) && true === $params['is_shell'])
		{
			$this->_is_shell = true;
		}
		
	}
	/**
	 * 运行触发器
	 */
	public function run()
	{
		if (true === $this->_is_shell)
		{
			$this->get_shell_param();
		} 
		$this->action();
	}

	protected function action()
	{
		$controller = pf_request::route_c();
		$action = pf_request::route_a();
		$module = pf_request::route_m(APP_NAME);
		if (empty($action))
		{
			$action = 'index';
		}

		if (empty($controller))
		{
			$controller = 'index';
		}

		if (empty($module))
		{
			$module = APP_NAME;
		}

		$_COOKIE['action']  = $action;
		$_COOKIE['controller']  = $controller;
		$controller .= $this->_controller_ext;

		$ctr_path = APP_PATH . $module . $this->_controller_path . $controller . '.php';

		if (is_file($ctr_path))
		{
			include_once $ctr_path; 
		} else {
			die("controller $controller is not exist![dir:$ctr_path]");
		}	 
		$obj_ctr = new $controller;
		if (method_exists($obj_ctr, $action))
		{
			$obj_ctr->$action();
		} else {
			die('_action not found!');
		}
	}
	
	/**
	 * 获取命令行参数
	 * @param $argv 例如: php shell.php c=index/a=index/name=shell
	 */
	protected function get_shell_param()
	{
		global $argc, $argv;
		echo 'this is a shell!' . "\n";
		if ($argc > 1)
		{		  
			$param = str_replace('/', '&', $argv[1]);
			parse_str($param, $_GET);
		}
		
	}

}
